<template>
  <div class="qi">
    <el-row style="width:100%;">
      <el-col :span="4">
        <!-- 这是侧导航 -->
        <tree
          :selGetData="selGetData"
          :searchData="searchData"
          :changeSearchData="changeSearchData"
          :selectId="selectId"
          :levStatus="levStatus"
          @setLevStatus="setLevStatus"
          @sbgetList="sbgetList"
          v-if="flag"
        ></tree>
      </el-col>
      <el-col :span="20">

        <div class="con-wrap" :class="">
          <!-- 这是组件要插入的地方 -->
          <div class="page-component-wrap animated fadeIn">
            <el-row style="margin:0px;margin-bottom: 10px;">
              <el-col :span="14">
                <div class="grid-content bg-purple-dark">
                  <el-autocomplete
                    v-model="searchText"
                    :fetch-suggestions="querySearchAsync"
                    :debounce="1000"
                    placeholder="内容22"
                    @select="handleSelect"
                    size="medium "
                    clearable
                    suffix-icon="el-icon-edit"
                    class="immm"
                  >
                    <template slot-scope="{ item }">
                      <span class="fullCodeNo">{{ item.fullCodeNo }}</span>
                      <span class="fullname">{{ item.fullname }}</span>
                      <!--<span class="level">{{ item.level }}</span>-->
                    </template>
                  </el-autocomplete>


                </div>

              </el-col>

              <el-col :span="10">
                <el-button type="success" @click="$refs.devref.handleCreate()" icon="el-icon-share">添加层级</el-button>
              </el-col>
            </el-row>

            <el-row v-show="searchSelectShow">
              <el-col :span="24">
                <div class="grid-content bg-purple-dark">
                  <el-form :inline="true" :model="formSearch" class="demo-form-inline">
                    <!--一级默认-->
                    <el-form-item>
                      <el-select v-model="selectId[0]" @change="currentSel($event, 0)" placeholder="请选择">
                        <el-option
                          v-for="it in selGetData[0]"
                          :key="it.id"
                          :label="it.selectText" c
                          :value="it.id">
                          <span style="float: left; color: #dc3b88; font-size: 13px">{{ it.codeNo}}&nbsp;</span>
                          <span style="float: left">{{ it.explainText}}</span>
                        </el-option>
                      </el-select>
                    </el-form-item>

                    <!--最后一级待选 如果空数组不显示-->
                    <template v-for="sel in selData">
                      <el-form-item v-if="(selGetData[sel.level]) && (selGetData[sel.level].length > 0)">
                        <el-select v-model="selectId[sel.level]" clearable @change="currentSel($event, sel.level)"
                                   placeholder="请选择">
                          <el-option
                            v-for="it in selGetData[sel.level]"
                            :key="it.id"
                            :label="it.selectText"
                            :value="it.id">
                            <span style="float: left; color: #dc3b88; font-size: 13px">{{ it.codeNo}}&nbsp;</span>
                            <span style="float: left">{{ it.explainText}}</span>
                          </el-option>
                        </el-select>
                      </el-form-item>

                    </template>

                    <el-form-item>
                      <el-button type="primary" @click="getList">搜索</el-button>
                      <!--<el-button type="success" @click="handleCreate" icon="el-icon-share">添加层级</el-button>-->
                    </el-form-item>
                  </el-form>
                </div>
              </el-col>
            </el-row>
            <!-- add edit item -->
            <device ref="devref"
                    :temps="temp"
                    :textMap="textMap"
                    :tData.sync="tData"
                    :levStatus="levStatus"
            ></device>
            <goods ref="goodsref"
                   :textMap="textMap"
                   :tData.sync="tData"
                   :levStatus="levStatus"
            ></goods>

            <el-table :data="list" v-loading.body="listLoading" border fit highlight-current-row
                      style="width: 100%;margin-left: 0%">
              <el-table-column align="center" label="序号" prop="id" width="80">
                <template slot-scope="scope"><span>{{scope.row.px}}</span></template>
              </el-table-column>
              <el-table-column align="center" label="层级" prop="level" width="50">
                <template slot-scope="scope"><span>{{scope.row.level}}</span></template>
              </el-table-column>
              <el-table-column align="left" label="层级名称" prop="fullname" width="400">
                <template slot-scope="scope"><span>{{scope.row.halfullName}}</span></template>
              </el-table-column>
              <el-table-column align="left" label="编码" prop="fullCodeNo" width="150">
                <template slot-scope="scope"><span>{{scope.row.fullCodeNo}}</span></template>
              </el-table-column>
              <el-table-column align="left" label="名称" prop="explainText">
                <template slot-scope="scope"><span>{{scope.row.ultimately?scope.row.explainText:'-'}}</span></template>
              </el-table-column>
              <el-table-column align="left" label="型号规格" prop="specification">
                <template slot-scope="scope"><span>{{scope.row.specification?scope.row.specification:'-'}}</span></template>
              </el-table-column>

              <el-table-column align="left" label="操作" fixed="right" width="240">
                <template slot-scope="scope">
                  <!--ultimately 为false 节点 调 codeExplains-->
                  <el-button v-if="!scope.row.ultimately" type="success" @click="$refs.devref.handleCreate2(scope.row)"
                             icon="el-icon-share"
                             size="mini"></el-button>
                  <el-button v-if="!scope.row.ultimately" type="primary" @click="$refs.goodsref.addGoods(scope.row)" icon="el-icon-plus"
                             size="mini"></el-button>
                  <el-button v-if="!scope.row.ultimately" type="warning" @click="$refs.devref.handleUpdate(scope.row)"
                             icon="el-icon-edit"
                             size="mini"></el-button>
                  <el-button v-if="!scope.row.ultimately" type="danger" @click="handleDelete(scope.row)"
                             icon="el-icon-delete"
                             size="mini"></el-button>
                  <!--ultimately 为true时 调商品 commodities接口 为节点时调 codeExplains-->
                  <el-button v-if="scope.row.ultimately" type="warning" @click="$refs.goodsref.updateGoods(scope.row)" icon="el-icon-edit"
                             size="mini"></el-button>
                  <el-button v-if="scope.row.ultimately" type="danger" @click="deleteGoods(scope.row)" icon="el-icon-delete"
                             size="mini"></el-button>

                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size"
                        @pagination="getList"/>

            <!--curd goods-->

          </div>
        </div>
      </el-col>
    </el-row>

  </div>
</template>
<script>
  // import TopBar from 'comp/TopBar'
  import tree from './comp/tree'
  // import 'filters/handleNum.js'

  import {fetchGet, createOne, deleteOne, deletePost, getOne, rolesAll, updateOneNoId} from '@/api/common'
  import {disableBtn, df, $err, $suc, ERRS, SUCS,$msg} from '@/utils'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  import device from './comp/deviceComp' // Secondary package based on el-pagination
  import goods from './comp/goodsComp' // Secondary package based on el-pagination

  export default {
    name: 'queryItem',
    computed: {

    },
    mounted() {
      this.getList()
      this.allList(0) //根级level select
    },
    data() {
      return {
        //弹出层
        listLoading: false,  //加载动画
        dialogStatus: '', //值对应textMap中的属性
        textMap: {
          update: '编辑层级',
          create: '添加层级',
          update2: '编辑备件',
          create2: '添加备件'
        },
        searchSelectShow:false, //搜索框select选中后 select多级下拉框展示
        //分页搜索
        total: 0,
        listQuery: {
          page: 1,
          size: 10,
          searchText: ''
        },
        list: [],     //内容
        restaurants: [],  //默认搜索值 [{ "aa": 11, "bb": "22" }]

        searchText: '',
        searchData: {},
        selData: [{}],   //搜索框选择后组成的遍历n 级select的数组
        changeSearchData:[{}],
        selGetData: [],  //多级select 根据level 请求api保存的数组
        flag: false,
        selectId: [],    //保存选择的多级 id
        levStatus: 0,  //select 级数
        tData: {}, //添加修改时保存父级信息

        formSearch: {},
        temp: {},
        tpgoods: {},




      };
    },

    methods: {
      setLevStatus(level) {
        this.levStatus = level
      },
      //add table px
      listAddPx() {
        let insIndex = this.listQuery.size * (this.listQuery.page - 1);
        this.list = this.list.map((v, index) => {
          this.$set(v, 'px', insIndex + index + 1);
          return v
        });
      },
      //搜索table数据
      getList() {
        this.total = 0;
        let fullCodeNo = ''
        if (this.levStatus > 0) {
          this.getChoseItem()
          fullCodeNo = this.tData.fullCodeNo
        }
        fetchGet(`codeExplains/condition?level=${this.levStatus}&page=${this.listQuery.page}&size=${this.listQuery.size}&searchText=${fullCodeNo}`).then(response => {
          let dat = response.data;
          if (dat.code == 0) {
            let data = dat.data.content;
            if (data.length > 0) {
              this.total = dat.data.totalElements; //共多少页
              this.listQuery.page = dat.data.page;
              var fib = function (n) {
                if (n.level > 1) {
                  return fib(n.parentCodeExplain) + '->' + n.explainText;
                } else {
                  return n.explainText
                }
              }

              var fib2 = function (n) {
                if (n.level > 1) {
                  return fib(n.parentCodeExplain) + '->' + n.explainText;
                } else {
                  return n.explainText
                }
              }
              this.list = []

              for (let v of data) {
                let te = v
                te.fullname = fib(v)
                if (v.ultimately) {
                  te.halfullName = v.parentCodeExplain ? fib(v.parentCodeExplain) : '-';
                } else {
                  te.halfullName = te.fullname
                }
                this.list.push(te)
              }
              this.listAddPx();
            } else {
              this.list = []
            }
          } else {
            ERRS(response.statusText)
          }

        })
      },

      //搜索table数据
      sbgetList(data) {
        this.searchSelectShow=false;
        // console.log(88888,data)
        this.tData = data
        let level=data.level;
        //改状态
        this.levStatus=level
        this.selectId[level-1]=data.id
        /*        if(data.leaf==true){
                  ERRS('该节点无子节点!');
                  return
                }*/
        this.total = 0;
        fetchGet(`codeExplains/condition?level=${level}&page=${this.listQuery.page}&size=${this.listQuery.size}&searchText=${data.fullCodeNo}`).then(response => {
          let dat = response.data;
          if (dat.code == 0) {
            let data = dat.data.content;
            if (data.length > 0) {
              this.total = dat.data.totalElements; //共多少页
              this.listQuery.page = dat.data.page;
              var fib = function (n) {
                if (n.level > 1) {
                  return fib(n.parentCodeExplain) + '->' + n.explainText;
                } else {
                  return n.explainText
                }
              }

              var fib2 = function (n) {
                if (n.level > 1) {
                  return fib(n.parentCodeExplain) + '->' + n.explainText;
                } else {
                  return n.explainText
                }
              }
              this.list = []

              for (let v of data) {
                let te = v
                te.fullname = fib(v)
                if (v.ultimately) {
                  te.halfullName = v.parentCodeExplain ? fib(v.parentCodeExplain) : '-';
                } else {
                  te.halfullName = te.fullname
                }
                this.list.push(te)
              }
              this.listAddPx();
            } else {
              this.list = []
            }
          } else {
            ERRS(response.statusText)
          }

        })
      },

      //输入间隔查询
      querySearchAsync(queryString, cb) {

        if (queryString.length > 0) {
          fetchGet(`codeExplains/condition?level=1&page=1&size=${this.listQuery.size}&searchText=${queryString}`).then(response => {
            let dat = response.data;
            if (dat.code == 0) {
              let data = dat.data.content;
              if (data.length > 0) {
                var fib = function (n) {
                  if (n.level > 1) {
                    return fib(n.parentCodeExplain) + '->' + n.explainText;
                  } else {
                    return n.explainText
                  }
                }
                var ret = []

                for (let v of data) {
                  let te = v
                  te.fullname = fib(v)
                  ret.push(te)
                }

                cb(ret);
                this.restaurants = ret

              } else {
                cb([]);
                this.restaurants = []
              }
            } else {
              ERRS(response.statusText)
            }
          })
        } else {
          // cb([]);
        }
      },
      //获得当前选择项
      getChoseItem() {
        let id = this.selectId[this.levStatus - 1]
        let data = this.selGetData[this.levStatus - 1].filter((v, index) => v.id == id);
        this.tData = data[0]
      },
      /*   // ---------curd----------*/

      //----------goods
      deleteGoods(row) {

        this.$msgbox({
          message: '确定要删除吗? ',
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(action => {
          deleteOne('commodities/codeExplains', {id: row.id}).then(res => {
            if (res.data.code === 0) {
              $suc('删除成功!')
              this.getList();
            } else {
              ERRS(res.data.message)
            }
          })
        });
      },

//----------item
      //删除
      handleDelete(row) {
        $msg('确定要删除该层级及所有子级吗? 该操作不可逆,请谨慎操作!!!').then(action => {
          deleteOne('codeExplains', {id: row.id}).then(res => {
            if (res.data.code === 0) {
              $suc('删除成功!')
              this.getList();
            } else {
              ERRS(res.data.message)
            }
          })
        });
      },


      //select change
      currentSel(pid, level) {
        this.levStatus = level + 1
        //selGetData lev+1的数组过滤掉,清空select
        this.selGetData = this.selGetData.filter((v, index) => index <= level);
        this.selectId = this.selectId.filter((v, index) => index <= level);
        this.selData = this.selData.filter((v, index) => index <= level);
        if (!pid) {
          this.levStatus--    //点击清空时,层级降1
          return;
        }
        //拉取下级select
        fetchGet(`codeExplains/child?parentId=${pid}`).then(response => {
          let dat = response.data;
          if (dat.code == 0) {

            let data = dat.data;
            //拼接 6 电气备件
            data.forEach((v, i) => {
              data[i].selectText = v.codeNo + ' ' + v.explainText
            });
            if (data.length > 0) {
              this.$set(this.selGetData, level + 1, data)
              this.$set(this.selData, level, {level: level + 1})
            } else {
              // console.log('nodata!')
            }
          } else {
            ERRS(dat.msg)
            // console.log('err',dat.msg)
            // console.log(response)
          }
        })
      },
      //递归算出select级数的数组
      sed(n) {
        let now = {
          id: n.id,
          codeNo: n.codeNo,
          fullCodeNo: n.fullCodeNo,
          explainText: n.explainText,
          level: n.level,
          leaf: n.leaf,
          ultimately: n.ultimately
        }
        this.selData.unshift(now)
        this.$set(this.selectId, n.level - 1, n.id)
        if (n.level > 1) {
          return this.sed(n.parentCodeExplain)
        } else {
          return
        }
      },
      //搜索结果选择
      handleSelect(item) {
        this.searchSelectShow=true;  //搜索下拉组件
        this.selData = []
        this.selectId = []
        this.searchText = item.fullCodeNo
        this.searchData = item
        this.levStatus = item.level
        this.sed(item)


        this.$set(this.selectId, this.levStatus, '') //多出一级待选的id
        //n 级select
        //每级的id是下级parentid 返回的数组给下级id 的select 选中 (最后一级是待选的)
        let pro=[];
        //用for of 对数组 遍历 转成map 取下标
        for(let [index,elem] of new Map( this.selData.map( ( item, i ) => [ i, item ] ) )){
          // console.log(779,index,elem);
          pro[index]=this.allList(elem)
        }
        //上面for中多重异步成功的时候 接受p1,p2,p3调用的resolve传递过来的data
        Promise.all(pro).then((res)=>{
          // console.log('...异步多重promise')
          // console.log(res[0]) //p1调用的结果
          // console.log(res[1])
          this.changeSearchData=this.selData;
        },(error)=>{  //一个失败全部失败了
          // console.log('promise',error);
        })
      },

      allList(arr) {
        var level = arr === 0 ? 0 : arr.level
        // console.log(arr);
        let url = arr === 0 ? `codeExplains/root` : `codeExplains/child?parentId=${this.selectId[level - 1]}`
        //异步
        return new Promise((resolve, reject) => {
          fetchGet(url).then(res => {
            // console.log(res);
            if (res.data.code === 0) {
              let dat = res.data;
              let data = dat.data;
              //拼接 6 电气备件
              data.forEach((v, i) => {
                data[i].selectText = v.codeNo + ' ' + v.explainText
              });
              this.$nextTick(() => {
                this.$set(this.selGetData, level, data)
                this.flag = true;
              })
              resolve(data);
            } else {
              ERRS(res.data.message)
              resolve(res.data.message);
            }
          }).catch(error => {
            reject(error)
          })
        })
        //  Promise end
      },
    },
    components: {
      'tree': tree,
      Pagination,
      device,
      goods
    }
  }
</script>

<style scoped lang="scss">
  .qi{
    display: flex;
    padding: 10px;
    border:0px solid blue;
    height: 100%;
  }
  .sel-row {
    margin-bottom: 20px;

    .sel-label {
      line-height: 36px;
    }
  }

  .ct {
    float: right;
    line-height: 21px;

    &:hover {
      color: #20a0ff;
      cursor: pointer;
    }
  }

  .el-row {
    margin: 10px 0;
  }

  .immm {
    width: 90%
  }

  body #app .con-wrap {
    padding-left: 1%;
  }

</style>

